API Call in Service Using HttpClient | Get & Display Data
API Call Using Service in Angular
In previous parts, API and Service were explained.
API is used to share data between backend and frontend.
Service is an Angular feature used to store common data, logic, and API calls.
API is not an Angular feature.
Service is an Angular feature.
Why API Call is Done Inside Service
API calls are kept inside services so they can be reused.
Common API calls, common data, and common logic are written in services.
Components only use the service to get data.
API Operations Used
With APIs, mainly four operations are used:
- Get data from backend
- Store data in backend
- Update data in backend
- Delete data from backend
Free APIs mostly allow only get data operations.
So here, a get API is used to display data.
Dummy API Used
A dummy products API is used from a dummy JSON website.
This API provides product data that can be displayed in the Angular app.
Creating Service
Service is created using Angular CLI.
Service is placed inside a services folder.
This keeps all services organized.
Service Code (API Call)
HttpClient is required to call APIs.
HttpClient must be imported.
get() method is used because data is fetched from API.
Using Service in Component
Service is injected inside the component using constructor.
API is called inside ngOnInit.
subscribe() is used because API data comes asynchronously.
Storing API Data
A signal is used to store product data.
API response data is set into the signal.
Displaying Data in HTML
Double curly braces are used for interpolation.
@for is used to loop over products.
Styling (CSS)
This helps separate each product visually.